import gradio as gr
import requests

# DeepSeek API 的 URL 和 API 密钥
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"  # 假设的 API URL
API_KEY = "sk-c42bb4f5f157478ab14ecb0029758ea7"  # 替换为你的 DeepSeek API 密钥


# 调用 DeepSeek API 的函数
def ask_deepseek(question):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",  # 假设的模型名称
        "messages": [{"role": "user", "content": question}]
    }

    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功
        result = response.json()
        return result["choices"][0]["message"]["content"]  # 假设返回的回答在 choices 中
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"
    except KeyError:
        return "无法解析 API 响应"


# 创建 Gradio 界面
def chat_interface(question):
    if not question.strip():
        return "请输入问题！"
    return ask_deepseek(question)


# 设置 Gradio 界面
interface = gr.Interface(
    fn=chat_interface,  # 调用聊天函数
    inputs="text",  # 输入框
    outputs="text",  # 输出框
    title="DeepSeek 问答系统",
    description="输入你的问题，DeepSeek 将为你解答。"
)

# 启动 Gradio 应用
interface.launch()